
//  XHLoginViewController.m
//  xinhua
//
//  Created by fengyn on 15/10/29.
//  Copyright © 2015年 lexingsoft. All rights reserved.
//

#import "XHLoginViewController.h"
#import "XHRegisterViewController.h"
#import "UINavigationController+YNBase.h"
#import "XHEditorPassWordViewController.h"

#import "Services.h"
#import "APIKey.h"
#import "AppDelegate.h"

#import <UIActionSheet+Blocks.h>
#import <UIAlertView+Blocks.h>
//#import "UMessage.h"

//#import "YunBaService.h"

@interface XHLoginViewController ()
//@property (weak, nonatomic) IBOutlet UIView *ui_inputBgView;
//@property (weak, nonatomic) IBOutlet UIView *ui_userView;


@property (weak, nonatomic) IBOutlet UITextField *ui_userTextField;
@property (weak, nonatomic) IBOutlet UITextField *ui_codeTextField;
@property (weak, nonatomic) IBOutlet UIButton *ui_codeButton;
@property (weak, nonatomic) IBOutlet UIButton *ui_loginButton;
@property (weak, nonatomic) IBOutlet UIView *ui_codeView;
@property (weak, nonatomic) IBOutlet UIView *ui_userView;
@property (weak, nonatomic) IBOutlet UIButton *ui_registerButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *la_loginViewBottom;

@property (strong, nonatomic) NSTimer *m_theTimer;
@property (assign, nonatomic) int waitingTime;
@property (strong, nonatomic) NSDictionary *m_smsResultDic;
@property (strong, nonatomic) NSString * m_error;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *la_height1;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *la_height2;

@end

@implementation XHLoginViewController

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.la_height1.constant = 0.5;
    self.la_height2.constant = 0.5;
    self.title = @"登录";
    [self.ui_loginButton setCornerRadius:4];
    
    [self.ui_codeView setCornerRadius:5];
    self.ui_codeView.layer.borderColor = [ColorManager colorWithHexString:@"#C4C4C4"].CGColor;
    self.ui_codeView.layer.borderWidth = 0.5;
    
    [self.ui_registerButton setCornerRadius:4];
    self.ui_registerButton.layer.borderColor = [ColorManager colorWithHexString:@"#5997A4"].CGColor;
    self.ui_registerButton.layer.borderWidth = 0.5;
    
    [self.ui_userView setCornerRadius:5];
    self.ui_userView.layer.borderColor = [ColorManager colorWithHexString:@"#C4C4C4"].CGColor;
    self.ui_userView.layer.borderWidth = 0.5;

    
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    dict[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:self.ui_codeTextField.placeholder attributes:dict];
//    [self.ui_codeTextField setAttributedPlaceholder:attribute];
//    
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    dic[NSForegroundColorAttributeName] = [UIColor whiteColor];
//    NSAttributedString *attributes = [[NSAttributedString alloc] initWithString:self.ui_userTextField.placeholder attributes:dic];
//    [self.ui_userTextField setAttributedPlaceholder:attributes];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.navigationController.navigationBar setTranslucent:YES];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"shouye-nav-bg"] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController setNavigationBarBottomLineHide:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.backIndicatorImage=nil;
//    self.navigationController.navigationBar.translucent=NO;
//    [self.navigationController setNavigationBarBottomLineHide:NO];
}

- (void)viewDidDisappear:(BOOL)animated{
    [self.m_theTimer invalidate];
    self.m_theTimer=nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)settingAction:(id)sender
{
    NSString * phone = @"";
    if([NSString checkNullString:[DataManager sharedInstance].servicePhone])
    {
        phone = telphone;
    }
    else
    {
        phone = [DataManager sharedInstance].servicePhone;
    }
}

- (void)showSmsCodeWaitView{
    self.ui_codeButton.enabled=NO;
    self.waitingTime=60;
    [self.ui_codeButton setTitle:[NSString stringWithFormat:@"%d秒后重发",self.waitingTime] forState:UIControlStateDisabled];
    self.m_theTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateSmsCodeWait) userInfo:nil repeats:YES];
}

- (void)updateSmsCodeWait
{
    self.waitingTime--;
    NSString *title=[NSString stringWithFormat:@"%d秒后重发",self.waitingTime];
    self.ui_codeButton.titleLabel.text=title;
    [self.ui_codeButton setTitle:title forState:UIControlStateDisabled];
    if (self.waitingTime<=0) {
        [self hideSmsCodeWaitView];
    }
}

- (void)hideSmsCodeWaitView{
    [self.m_theTimer invalidate];
    [self.ui_codeButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    self.ui_codeButton.enabled=YES;
}

- (BOOL)isCanGetSMSCode{
    if (![NSString checkPhoneString:self.ui_userTextField.text]) {
        return NO;
    }
    return YES;
}

- (IBAction)getCodeAction:(id)sender {
    if ([self isCanGetSMSCode]) {
        [self showSmsCodeWaitView];
        [self.ui_codeTextField becomeFirstResponder];
        [ServiceManager getMessageCodeWithPhone:self.ui_userTextField.text success:^(NSDictionary *data) {
            self.m_smsResultDic=data;
            DLog(@"发送短信验证码：成功");
            [PromptAction showSuccessPrompt:@"验证码成功发送"];
        } failure:^{
            DLog(@"发送短信验证码：失败");
        }];
    }
}

- (BOOL)isCanLogin{
    if ([testAcount isEqualToString:self.ui_userTextField.text]&&![NSString checkNullString:self.ui_codeTextField.text]) {
        return YES;
        //特殊帐号验证
    }
    if (![NSString checkPhoneString:self.ui_userTextField.text]){
//        [PromptAction showErrorPrompt:@"请输入手机号"];
        return NO;
    }
//    if (!self.m_smsResultDic) {
//        [PromptAction showErrorPrompt:@"请获取验证码"];
//        return NO;
//    }
    if ([NSString checkNullString:self.ui_codeTextField.text]) {
        [PromptAction showErrorPrompt:@"请输入密码"];
        return NO;
    }
//    if (![self.ui_codeTextField.text isEqualToString:self.m_smsResultDic[@"identifyingCode"]]) {
//        [PromptAction showErrorPrompt:@"验证码错误"];
//        return NO;
//    }
    return YES;
}

- (IBAction)backAction:(id)sender {
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)successAction{
//    AppDelegate *delegate=[UIApplication sharedApplication].delegate;
//    [delegate finishLaunching];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)loginAction:(id)sender {
    [self.view endEditing:YES];
    if ([self isCanLogin]) {
        WS(weakSelf)
        [ServiceManager loginWithPhone:self.ui_userTextField.text passWord:self.ui_codeTextField.text success:^(NSDictionary *data) {
            if ([[DataManager sharedInstance] isLogin])
            {
               
            }
            NSLog(@"%@",[DataManager sharedInstance].userId);
            [PromptAction showSuccessPrompt:@"登录成功"];
            //            [UMessage setAlias:[DataManager sharedInstance].userId type:@"userId" response:^(id responseObject, NSError *error) {
            //            }];
            [weakSelf.ui_loginButton setHidden:NO];
            [weakSelf successAction];
            
        } failure:^(NSDictionary *failure) {
            
            if ([failure[@"message"]isEqualToString:@"PASSWORD_ERROR--密码错误,输入密码不匹配"])
            {
                UIAlertView *alertView=[[UIAlertView alloc] init];
                alertView.alertViewStyle=UIAlertViewStyleDefault;
                alertView.title=@"密码错误";
                alertView.message = @"输入密码不匹配";
                RIButtonItem *cancelItem=[RIButtonItem itemWithLabel:@"重试"];
                RIButtonItem *okItem=[RIButtonItem itemWithLabel:@"忘记密码" action:^{
                    XHEditorPassWordViewController * viewController = [[XHEditorPassWordViewController alloc]init];
                    viewController.title = @"修改密码";
                    viewController.phone = self.ui_userTextField.text;
                    [self.navigationController pushViewController:viewController animated:YES];
                    
                }];
                [alertView addButtonItem:cancelItem];
                [alertView addButtonItem:okItem];
                [alertView show];
            }
            else
            {
                [PromptAction showErrorPrompt:[NSString stringWithFormat:@"%@",failure[@"message"]]];
            }
        }];
    }

}

///注册
- (IBAction)registerAction:(id)sender
{
    XHRegisterViewController * viewController = [[XHRegisterViewController alloc]init];
    viewController.title = @"注册";
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)bgTouchAction:(id)sender {
    [self.view endEditing:YES];
}

#pragma mark - KeyBoardNotification
- (void)keyboardWillShowNotification:(NSNotification *)notif{
    float animationTime=[[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGFloat keyboardHeight=[notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    WS(weakSelf)
    [UIView animateWithDuration:animationTime animations:^{
        CGFloat constant=weakSelf.la_loginViewBottom.constant;
        weakSelf.la_loginViewBottom.constant=keyboardHeight > constant ? keyboardHeight : constant;
        [weakSelf.view layoutIfNeeded];
    }];
}

- (void)keyboardWillHideNotification:(NSNotification *)notif{
    float animationTime=[[notif.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    WS(weakSelf)
    [UIView animateWithDuration:animationTime animations:^{
        weakSelf.la_loginViewBottom.constant=150;
        [weakSelf.view layoutIfNeeded];
    }];
}

@end
